import React, { Component } from 'react'
import Highlighter from 'react-highlight-words'
import { history } from 'umi'
import {
  Icon,
  message,
  Button,
  Table,
  Switch,
  Divider,
  Tag,
  Popconfirm,
  Input,
  Tooltip,
} from 'antd'
import { getCommentList, changeCommentStatus, deleteCommentById } from '@/services/admin'
import './index.less'
import moment from 'moment'
import { articleBaseUrl } from '@/assets/js/ConstVariable'
export default class ArticleList extends Component {
  state = {
    list: [],
    searchText: '',
    searchedColumn: '',
  }

  componentDidMount() {
    this.getArticleList()

    document.title = '评论管理'
  }
  // 获取文章列表
  getArticleList = async () => {
    const res = await getCommentList()
    if (res?.status === 200) {
      message.destroy()
      message.success('获取评论列表成功')
      this.setState({ list: res.data })
    }
  }

  // 删除评论
  handleDelete = async (id) => {
    const res = await deleteCommentById(id)
    if (res?.status === 200) {
      message.success('删除评论成功~')
      this.getArticleList()
    }
  }

  // 编辑评论
  changeCommentStatus = (id, status) => {
    changeCommentStatus(id, status)
  }

  // 表格自定义过滤
  getColumnSearchProps = (dataIndex) => ({
    filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
      <div style={{ padding: 8 }}>
        <Input
          ref={(node) => {
            this.searchInput = node
          }}
          placeholder={`请输入标题`}
          value={selectedKeys[0]}
          onChange={(e) => setSelectedKeys(e.target.value ? [e.target.value] : [])}
          onPressEnter={() => this.handleSearch(selectedKeys, confirm, dataIndex)}
          style={{ width: 188, marginBottom: 8, display: 'block' }}
        />
        <Button
          type="primary"
          onClick={() => this.handleSearch(selectedKeys, confirm, dataIndex)}
          icon="search"
          size="small"
          style={{ width: 90, marginRight: 8 }}
        >
          搜索
        </Button>
        <Button onClick={() => this.handleReset(clearFilters)} size="small" style={{ width: 90 }}>
          重置
        </Button>
      </div>
    ),
    filterIcon: (filtered) => (
      <Icon type="search" style={{ color: filtered ? '#1890ff' : undefined }} />
    ),
    onFilter: (value, record) =>
      record[dataIndex].toString().toLowerCase().includes(value.toLowerCase()),
    onFilterDropdownVisibleChange: (visible) => {
      if (visible) {
        setTimeout(() => this.searchInput.select())
      }
    },
    render: (text, record) =>
      this.state.searchedColumn === dataIndex ? (
        <a href="" href={articleBaseUrl + '#/detail/' + record.id} target="_blank">
          <Highlighter
            highlightStyle={{ backgroundColor: '#ffc069', padding: 2 }}
            searchWords={[this.state.searchText]}
            autoEscape
            textToHighlight={text.toString()}
          />
        </a>
      ) : (
        <a href={articleBaseUrl + '/#/detail/' + record.articleId} target="_blank">
          {text}
        </a>
      ),
  })

  // 搜索
  handleSearch = (selectedKeys, confirm, dataIndex) => {
    confirm()
    this.setState({
      searchText: selectedKeys[0],
      searchedColumn: dataIndex,
    })
  }

  // 重置
  handleReset = (clearFilters) => {
    clearFilters()
    this.setState({ searchText: '' })
  }

  render() {
    const { list } = this.state
    const columns = [
      {
        title: '标题',
        dataIndex: 'title',
        key: 'title',
        ...this.getColumnSearchProps('title'),
      },
      {
        title: '评论',
        dataIndex: 'content',
        key: 'content',
        ...this.getColumnSearchProps('content'),
      },
      {
        title: '发布时间',
        dataIndex: 'addTime',
        key: 'addTime',
        width: 160,
        render: (addTime) => <a>{moment(addTime * 1000).format('YYYY-MM-DD HH:ss')}</a>,
        sorter: (a, b) => moment(a.addTime * 1000).unix() - moment(b.addTime * 1000).unix(),
      },
      {
        title: '点赞数',
        key: 'liked',
        dataIndex: 'liked',
        width: 100,
        render: (liked) => {
          return (
            <span>
              <Tag color="tomato">{liked}</Tag>
            </span>
          )
        },
        sorter: (a, b) => a.liked - b.liked,
      },
      {
        title: '讨厌值',
        key: 'disliked',
        dataIndex: 'disliked',
        width: 100,
        render: (disliked) => {
          return (
            <span>
              <Tag color="gray">{disliked}</Tag>
            </span>
          )
        },
        sorter: (a, b) => a.disliked - b.disliked,
      },

      {
        title: '审核',
        key: 'status',
        dataIndex: 'status',
        width: 70,
        filters: [
          {
            text: '通过',
            value: 1,
          },
          {
            text: '未通过/未处理',
            value: 0,
          },
        ],
        onFilter: (value, record) => record.status === value,
        width: 100,
        render: (status, record) => {
          return (
            <span>
              <Switch
                defaultChecked={status === 1}
                onChange={(value) => this.changeCommentStatus(record.id, value)}
              />
            </span>
          )
        },
      },
      {
        title: '操作',
        key: 'author',
        render: (text, record) => (
          <span>
            <Popconfirm
              title="确认要删除吗？"
              okText="确认"
              cancelText="取消"
              onConfirm={() => this.handleDelete(record.id)}
            >
              <a>删除</a>
            </Popconfirm>
          </span>
        ),
      },
    ]

    return (
      <div>
        <Table
          className="comment-table"
          bordered
          columns={columns}
          dataSource={this.state.list}
          rowKey={(record) => record.id}
        />
      </div>
    )
  }
}
